/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Model;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.Vector;


/**
 *
 * @author vf
 */
public class Clock {

    private long time;
    private long lastUpdate;
    private long startTime;
    private Vector<ClockListener> listeners;

    public Clock(){
        time=0;
        startTime=0;
        lastUpdate=0;
        listeners=new Vector<ClockListener>();
    }

    public void addListener(ClockListener listener){
        if(!listeners.contains(listener))
            listeners.add(listener);

        listener.clockUpdated(new ClockEvent(this));
    }

    public void update(long dtime){
        if(startTime==0) startTime=(new Date()).getTime();
        //lastUpdate=time;
        time=(new Date()).getTime()-startTime;
        //System.out.println("start time : "+startTime+"time: "+time+" last update: "+lastUpdate);
        if (time-lastUpdate > 1000)
            clockUpdated();
    }

    private void clockUpdated(){
        for(ClockListener listener : listeners)
            listener.clockUpdated(new ClockEvent(this));
    }

    public BufferedImage getImage(){
        lastUpdate=time;
        //System.out.println("clock time : "+time);
        int totalSecs=(int)((time-(time%1000))/1000);

        int m=(int)((totalSecs-(totalSecs%60))/60);
        int s=(int)totalSecs%60;

        String z1 = new String("");
        String z2 = new String("");
        if (m<10)
            z1="0";
        if (s<10)
            z2="0";
        //System.out.println("total secs : "+totalSecs+" minutes: "+m+" seconds: "+s);
        
        String stringTime = new String();
        stringTime=z1+m+":"+z2+s;

        BufferedImage image = new BufferedImage(137, 64, BufferedImage.TYPE_INT_ARGB);
        Graphics buffer = image.getGraphics();

        
        buffer.setColor(Color.WHITE);
        buffer.setFont(new Font("Monospaced", Font.BOLD, 33));
        buffer.drawChars(stringTime.toCharArray(), 0, stringTime.length(), 16, 41);

        return image;
    }
}
